package com.wechat.login;

import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.StandardOpenOption;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * 登录锁定
 * 
 * @author 618lf
 */
@Getter
@Setter
@Accessors(chain = true)
public class LoginLock {

	private final File file;
	private final FileChannel channel;
	private final FileLock lock;

	public LoginLock(File file) throws IOException {
		this.file = file;
		this.channel = FileChannel.open(this.file.toPath(), StandardOpenOption.WRITE);
		this.lock = this.channel.tryLock();
	}

	public boolean isLocked() {
		return lock != null;
	}

	public void release() throws IOException {
		this.lock.close();
		this.channel.close();
		this.file.delete();
	}
}